#!/bin/bash

echo "=================================================="
echo "         AutoRun 自动化脚本管理平台 启动脚本"
echo "=================================================="

# 解析启动选项
BACKEND_ONLY=false
FRONTEND_ONLY=false

while [[ $# -gt 0 ]]; do
    case $1 in
        --backend-only)
            BACKEND_ONLY=true
            shift
            ;;
        --frontend-only)
            FRONTEND_ONLY=true
            shift
            ;;
        -h|--help)
            echo "用法: $0 [选项]"
            echo "选项:"
            echo "  --backend-only   只启动后端服务"
            echo "  --frontend-only  只启动前端服务"
            echo "  --help           显示帮助信息"
            echo ""
            echo "默认同时启动前后端服务"
            exit 0
            ;;
        *)
            echo "未知选项: $1"
            echo "使用 --help 查看帮助信息"
            exit 1
            ;;
    esac
done

# 启动后端服务
start_backend() {
    echo "🚀 启动Java后端服务..."
    
    cd backend
    
    echo "📦 编译Java项目..."
    mvn clean package -DskipTests -q
    
    if [ ! -f "target/autorun-server-1.0.0.jar" ]; then
        echo "❌ 编译失败，未找到JAR文件"
        exit 1
    fi
    
    echo "🔧 设置环境变量..."
    export DB_NAME=autorun_db
    export SERVER_PORT=8891
    export JWT_SECRET=autorun-script-control-center-jwt-secret-2024
    
    echo "▶️  启动Java后端服务 (端口: 8891)..."
    nohup java -jar target/autorun-server-1.0.0.jar > ../backend.log 2>&1 &
    echo "✅ 后端服务已启动 (PID: $!)"
    
    cd ..
}

# 启动前端服务
start_frontend() {
    echo "🎨 启动前端服务..."
    
    cd frontend
    
    echo "📦 检查前端依赖..."
    if [ ! -d "node_modules" ]; then
        echo "安装前端依赖..."
        npm install
    fi
    
    echo "▶️  启动前端开发服务器 (端口: 8081)..."
    nohup npm run dev > ../frontend.log 2>&1 &
    echo "✅ 前端服务已启动 (PID: $!)"
    
    cd ..
}

# 主流程
if [ "$FRONTEND_ONLY" = true ]; then
    start_frontend
    echo ""
    echo "🎉 前端服务启动完成！"
    echo "   访问地址: http://localhost:8081"
    
elif [ "$BACKEND_ONLY" = true ]; then
    start_backend
    echo ""
    echo "🎉 后端服务启动完成！"
    echo "   API地址: http://localhost:8891"
    
else
    # 同时启动前后端
    start_backend
    start_frontend
    
    echo ""
    echo "🎉 AutoRun 启动完成！"
    echo "   前端：http://localhost:8081"
    echo "   后端：http://localhost:8891"
fi

echo ""
echo "📋 日志文件："
echo "   后端日志: backend.log"
echo "   前端日志: frontend.log"
echo ""
echo "使用 ./stop.sh 停止服务"